package study.web.blog;

import java.util.List;

import javax.annotation.Resource;
import javax.validation.Valid;

import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import study.domain.blog.Post;
import study.domain.user.User;
import study.service.blog.BlogService;
import study.service.user.UserService;
import study.service.web.SessionService;

import com.barney.support.web.WebList;

@Controller
@RequestMapping(value = "/blog/{username}")
public class PostController {

	@Resource(name = "blogService")
	private BlogService blogService;

	@Resource(name = "userService")
	private UserService userService;

	@Resource(name = "sessionService")
	private SessionService sessionService;

	@RequestMapping(value = "", method = RequestMethod.GET)
	public String list(@PathVariable("username") String username, Model model) {
		User user = userService.getUserByUsername(username);
		if(user == null) {
			throw new RuntimeException("NOT FOUND user "+username);
		}
		User currentUser = sessionService.getCurrentUser();

		WebList<Post> result = new WebList<Post>();
		result.setList(blogService.getPosts(user.getUserId()));

		model.addAttribute("username" , username);
		model.addAttribute("result", result);
		if(currentUser != null && user.getUserId().equals(currentUser.getUserId())) {
			model.addAttribute("command", new Post());
		}
		return "/blog/list";
	}

	@RequestMapping(value = "/{postId}", method = RequestMethod.GET)
	public String show(@PathVariable("username") String username,
			@PathVariable("postId") Long postId, Model model) {
		Post post = blogService.getPost(postId);
		model.addAttribute("post", post);
		return "/blog/show";
	}

	@PreAuthorize("hasRole('ROLE_USER')")
	@RequestMapping(value = "/post", method = RequestMethod.POST)
	public String post(@Valid @ModelAttribute(value = "post") Post post,
			BindingResult bindingResult,
			@RequestParam(value = "attachmentId", required = false) List<String> attachmentIds) {
		if (bindingResult.hasErrors()) {
			StringBuilder builder = new StringBuilder();
			for (FieldError fe : bindingResult.getFieldErrors()) {
				builder.append("Post Field Error : ")
						.append(fe.getField()).append(" - ")
						.append(fe.getRejectedValue()).append("; ");
			}
			throw new RuntimeException("Post Error "+builder.toString());
		}
		User currentUser = sessionService.getCurrentUser();
		blogService.addPost(currentUser, post, attachmentIds);
		//return "redirect:/blog/"+currentUser.getUsername();
		return null;
	}
}
